from core.tools.short_message import ShortMessage
from django.utils import timezone
import random
import datetime
from django.db import models
from django.db.models import F
from finance_c2c.settings import LHValidateCodeID, LHValidateCodeKey


class ShortMsgManager(models.Manager):
    def sms_code(self, code, tel):
        info = self.filter(code=code, tel=tel)
        if info.exists():
            info_obj = info.first()
            if info_obj.status:
                info_obj.status = False
                info_obj.save()
                return True, None
            else:
                return False, "验证码已被使用过了"
        else:
            return False, "验证码不正确"


class ShortMsg(models.Model):
    """
    短信验证
    """
    tel = models.CharField(verbose_name="手机号", max_length=16, db_index=True)
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="更新时间")
    update_time = models.DateTimeField(verbose_name="更新时间", blank=True, null=True)
    code = models.IntegerField(verbose_name="验证码", blank=True, null=True)
    num = models.IntegerField(verbose_name="数量", blank=True, null=True)
    status = models.BooleanField(default=True)
    objects = ShortMsgManager()

    class Meta:
        verbose_name = "手机验证码"  # admin后台显示
        verbose_name_plural = verbose_name  # 复数显示

    def get_update_time(self):
        """
        :return:
        """
        now_time = datetime.datetime.now()
        delta = datetime.timedelta(seconds=60)
        if not self.update_time or self.update_time < now_time - delta:
            return True
        else:
            return False

    def send_code(self, template_id=133521, appid=LHValidateCodeID, appkey=LHValidateCodeKey):
        code = random.randint(1000, 9999)
        today = datetime.datetime.today()
        now_time = datetime.datetime(today.year, today.month, today.day)
        if not self.update_time:
            update_time = None
        else:
            update_time = datetime.datetime(self.update_time.year, self.update_time.month, self.update_time.day)
        resp = ShortMessage.send_single(self.tel, code, template_id, appid, appkey)
        if resp.get("result") == 0 and resp.get("errmsg") == 'OK':
            self.code = code
            if now_time != update_time:
                self.num = 1
            else:
                self.num = F('num') + 1
            self.update_time = datetime.datetime.now()
            self.status = True
            self.save()
            return True
        else:
            return False


class Province(models.Model):
    # 省份及代码
    code = models.CharField(max_length=20, verbose_name="省份代码", unique=True)
    name = models.CharField(max_length=255, verbose_name="省份名称")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '省份及代码'
        verbose_name_plural = verbose_name


class City(models.Model):
    # 城市及代码
    code = models.CharField(max_length=20, verbose_name="城市代码", unique=True)
    name = models.CharField(max_length=255, verbose_name="城市名称", blank=True, null=True)
    province = models.ForeignKey("Province", verbose_name="所属省份", related_name="province_city")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '城市及代码'
        verbose_name_plural = verbose_name


class District(models.Model):
    # 区县及代码
    code = models.CharField(max_length=20, verbose_name="区县代码", unique=True)
    name = models.CharField(max_length=255, verbose_name="区县名称", blank=True, null=True)
    city = models.ForeignKey("City", verbose_name="所属城市", related_name="city_district")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '区县及代码'
        verbose_name_plural = verbose_name


class BankCode(models.Model):
    name = models.CharField(verbose_name="银行名称", max_length=16)
    code = models.CharField(verbose_name="银行code，微信需要用", max_length=16)
    sign = models.CharField(verbose_name="标识，前端需要匹配", max_length=16)

    class Meta:
        verbose_name = "银行编号"
        verbose_name_plural = verbose_name


class PublicPrivate(models.Model):
    fileType = ((1, "对方公司提供的"), (2, "我方公司生成的"))
    signType = ((1, "APPID签名"), (2, "商户签名"), (3, "不涉及签名方式"))
    public_file = models.FileField(verbose_name="公钥文件", upload_to="PublicPrivate")
    private_file = models.FileField(verbose_name="私钥文件", upload_to="PublicPrivate")
    file_type = models.IntegerField(verbose_name="提供类型", db_index=True, choices=fileType)
    func_type = models.CharField(max_length=20, verbose_name="文件作用", db_index=True, help_text="支付,转账,登录，其他")
    company = models.CharField(verbose_name="对应的公司", max_length=64)
    channel_key = models.CharField(verbose_name="渠道key", max_length=64, default="youpinhuiyuan")
    app_id = models.CharField(verbose_name="通联渠道号", max_length=64, db_index=True, default="")
    TLMchId = models.CharField(verbose_name="通联商户号", max_length=64, db_index=True, default="")
    sign_type = models.IntegerField(default=2, db_index=True, verbose_name="签名方式", choices=signType)

    class Meta:
        verbose_name = "公私钥对"
        verbose_name_plural = verbose_name


# 添加群聊二维码
class QrCodeGroupChat(models.Model):
    img = models.ImageField(upload_to="qunLiao/", verbose_name="群聊图片")
    description = models.CharField(max_length=16, verbose_name="描述")

    class Meta:
        verbose_name = "添加群聊二维码"
        verbose_name_plural = verbose_name

# task储存结果
# class TasksResult(models.Model):
#     task_id = models.CharField(max_length=191, verbose_name="任务id")
#     result = models.TextField(verbose_name="结果")
#     create_time = models.DateTimeField(default=timezone.now)
#
#     class Meta:
#         verbose_name = "task储存结果"
#         verbose_name_plural = verbose_name
